import LanguageMng from "./LanguageMng";
import GameWS from "./GameWS";
import PoolRoom from "../Entities/PoolRoom";
import DealRoom from "../Entities/DealRoom";
import PointRoom from "../Entities/PointRoom";
import {HubConnectionState} from "../libs/signalr/HubConnection";
import LogicConfigTs from "../Utils/LogicConfigTs";
import LanguageMngTs from "./LanguageMngTs";
import GameLogicUtilTs from "../Utils/GameLogicUtilTs";

cc.Class({
    extends: cc.Component,

    properties: {

        pokerStackNode:{
            default:null,
            type:cc.Node
        },

        playerSeat:{
            default:null,
            type:cc.Node
        },

        opponentSeatParent:{
            default:null,
            type:cc.Node
        },

        compareParent:{
            default:null,
            type:cc.Node
        },

        uiMgrNode:{
            default:null,
            type:cc.Node,
        },

        uiMgr:{
            default:null,
            type:cc.Component
        },

    },

    onLoad () {
        this._roomObj = {}
        this._initBase()
    },

    _initBase:function () {
        if(!cc.gg){
            cc.gg = {}
        }
        cc.gg.tpgMgr = this
        // cc.log("基类onLoad")
        this._committingUsers = []
        this.initGameMgr()

        this._onBackground = function(){
            console.log("=======Game run in background=======");
        }
        this._onFront = async function(){
            console.log("=======Game run in front=======");
            await cc.gg.toastMgr.showNetWaitting()
            cc.find("Canvas").emit("msgwatcher_add",function () {
                let sceneName = cc.director.getScene().name
                if(GameWS.getState() === HubConnectionState.Connected){
                    GameLogicUtilTs.needStopDispatching = true
                    if(sceneName === "LobbyBlue"){
                        cc.gg.toastMgr.removeNetWaitting()
                        return true
                    }
                    //refresh table with exsists data
                    this._clearTable(this.gameState)
                    // cc.gg.dataMgr.clearRoomData()
                    // this.gameRefreshTable()
                    this.scheduleOnce(function () {
                        cc.gg.toastMgr.removeNetWaitting()
                        if(sceneName === LogicConfigTs.SCENENAME_GAME_2){
                            cc.gg.gameDataUtil.goToTwoPlayerGame()
                        }else if(sceneName === LogicConfigTs.SCENENAME_GAME_6){
                            cc.gg.gameDataUtil.goToSixPlayerGame()
                        }
                    },1)
                    return true
                }
                return false
            }.bind(this))

            //disconnect
            // GameWS.stopConnection()
        }
        cc.game.on(cc.game.EVENT_HIDE,this._onBackground ,this);
        cc.game.on(cc.game.EVENT_SHOW, this._onFront,this)

        this.initGameUI()
    },

    start () {
        let isPointRoom = cc.gg.dataMgr.room instanceof PointRoom
        this.uiMgrNode.emit("ui_show_btn_deals",!isPointRoom)

    },

    sendTdData:function () {

        if(cc.gg.dataMgr.playGuild){
            cc.gg.tdUtil.doSendTdEvent("open_guild_table",null)
        }else{
            cc.gg.tdUtil.doSendTdEvent("open_table",null)
        }
    },

    onDestroy(){
        cc.game.off(cc.game.EVENT_HIDE,this._onBackground ,this);
        cc.game.off(cc.game.EVENT_SHOW, this._onFront,this)
    },

    initGameUI:function () {
        this._initSeats()
        //deck node
        this.pokerStackNode.originPos = cc.v2(this.pokerStackNode.position.x,this.pokerStackNode.position.y)
        this.compareParent.active = false

        this.handPokerParent.getComponent("HandPokerParent").initHandPokerParent(this,this.uiMgr,this.finishSlotNode.getBoundingBoxToWorld(),this.disPokerStack.getBoundingBoxToWorld())

        cc.loader.loadRes("uis/OptionUIs",cc.Prefab,function (err, prefab) {
            let newNode = cc.instantiate(prefab)
            let uiMgr = this.uiMgrNode.getComponent("GameUIMgr")
            uiMgr.btnParent.addChild(newNode)
            uiMgr.optNode = newNode
        }.bind(this))

        if(!CC_DEBUG){
            let testContent = cc.find("testContent",this.node)
            if(testContent) testContent.active = false
        }
    },

    _initSeats(){
        let comNodes = this.compareParent.children
        let oppSeatNodes = this.opponentSeatParent.children
        for(let i=0;i<oppSeatNodes.length;i++){
            let node = oppSeatNodes[i]
            let seat = node.getComponent("UserSeat")
            seat.initSeat(null)
        }
    },

    // async enterGame(type, mode, joker){
    //     return GameWS.findRoom(type, mode, joker)
    // },

    onGameReconnect:function (cb) {
        if(cc.gg.dataMgr.isReconnect){
            //start to collect info
            cc.find("Canvas").emit("msgwatcher_add",function () {
                if(cc.gg.dataMgr.room && cc.gg.baseUtil.getMapLength(cc.gg.dataMgr.users) === cc.gg.dataMgr.room.p_max){
                    if(cb) cb()
                    this._refreshTableUnderReconnecting()
                    return true
                }
                return false
            }.bind(this))
        }
    },

    // gameRefreshTable:function () {
    //     this._refreshTableUnderReconnecting(true)
    // },

    initGameMgr:function () {
        this.node.on("flow_player_turn",this.onPlayerTurnStart.bind(this),this)
        this.node.on("flow_opponent_discard",this.opponentDiscardOnePoker.bind(this),this)
        this.node.on("flow_start_group_passive",this._onFlowStartGroupPassive.bind(this),this)
        this.node.on("flow_calculating",this._onFlowCalculating.bind(this),this)
        this.node.on("flow_shuffle",this._onFlowShuffle.bind(this),this)
        this.node.on("player_option_discard",this.startDiscardFlow.bind(this),this)
        this.node.on("ui_update_head_score",this._onUIUpdateHeadScore.bind(this),this)
        this.node.on("flow_grab_player_finish",this._onGrabPlayerFinish.bind(this),this)
        // this.node.on("game_start_reconnect",this._onStartReconnecting.bind(this),this)
        this.node.on("user_leave",this._onUserLeave.bind(this),this)
        this.node.on("user_destroy",this._onUserDestroy.bind(this),this)
        this.node.on("game_init_user_score",this._onGameInitUserScore.bind(this),this)
        this.node.on("anim_hand_pokers_fly",this._onHandPokerFly.bind(this),this)

        this.node.on("option_select_node",this.onOptionSelectNode.bind(this),this)
        this.node.on("player_discard_passive",this.startDiscardFlowPassive.bind(this),this)

        this.node.on("game_room_destroy",this.onGameRoomDestroy.bind(this),this)
        this.node.on("reset_table",this._clearTable.bind(this),this)
        this.node.on("close_windows",this.closeWindows.bind(this),this)
        this.node.on("close_dialogs",this.closeDialogs.bind(this),this)

        this.node.on("dealinfo_count_down_finish",this._onDealInfoCountDownFinish.bind(this),this)

        this.node.on("opt_btn_discard",this._onOptBtnDiscard.bind(this),this)
        this.node.on("opt_btn_finish",this._onOptBtnFinish.bind(this),this)
        this.node.on("opt_btn_group",this._onOptBtnGroup.bind(this),this)
        this.node.on("opt_btn_drop",this._onOptBtnDrop.bind(this),this)

        // this.node.on("drag_to_finish",this._onDragToFinish.bind(this),this)
    },

    addCommittingUser:function (user) {
        cc.log("增加等待提交手牌玩家",user)
        if(this._committingUsers.indexOf(user) > -1)
            return

        this._committingUsers.push(user)
    },

    getCommittingUsers:function () {
        return this._committingUsers
    },

    clearCommittingUser:function (user) {
        cc.log("清理单个等待提交手牌玩家,让头像变为已提交状态",user)
        let idx = this._committingUsers.indexOf(user)
        if(idx < 0)
            return

        let seatNode = this.getSeatByUID(user.id)
        let script = seatNode.getComponent("SeatOther")
        if(!script){
            script = seatNode.getComponent("TPPHead")
        }
        script.stopCountting()
        this._committingUsers.splice(idx,1)
    },

    clearAllCommittingUsers:function () {
        cc.log("清理所有等待提交手牌玩家")
        this._committingUsers = []
    },

    testShuffle:function () {
        cc.find("Canvas").emit("flow_shuffle")
    },

    onGameTestButtonClicked:function (event) {
        let btnName = event.target.name
        if(btnName === "b1"){
            this.testShuffle()
        }else if(btnName === "b2"){
            this._clearTable(this.gameState)
            // this.gameRefreshTable()
        }else if(btnName === "b3"){
            cc.gg.baseUtil._onBackPressed()
        }
    },

    backToLobby:function (cbYes,cbCancel,cbDirecotory) {
        let nowRoom = cc.gg.dataMgr.room
        // if(nowRoom.state !== cc.gg.enumConfig.RoomNetState.IN_GAME
        // && nowRoom.state !== cc.gg.enumConfig.RoomNetState.PLAYING
        // && nowRoom.state !== cc.gg.enumConfig.RoomNetState.GAMEINTERVAL
        //     && nowRoom.state !== cc.gg.enumConfig.RoomNetState.COUNTTING){
        //     cc.gg.dataMgr.getPlayerUser().leave()
        //     return
        // }

        let inGame = nowRoom.state === cc.gg.enumConfig.RoomNetState.IN_GAME
            || nowRoom.state === cc.gg.enumConfig.RoomNetState.PLAYING
            || nowRoom.state === cc.gg.enumConfig.RoomNetState.COMMITTING
            || nowRoom.state === cc.gg.enumConfig.RoomNetState.COUNTTING

        if(nowRoom instanceof PointRoom){
            if(inGame){
                let title = LanguageMng.getSentence(3)
                let positiveStr = LanguageMng.getSentence(57)   //Yes
                let passiveStr = LanguageMng.getSentence(179)   //Cancel
                let content = LanguageMng.getSentence(185)  //are u sure to back to lobby
                cc.gg.toastMgr.showDialog(title,positiveStr,passiveStr,content,
                    function () {
                        if(cbYes) cbYes()
                        cc.gg.dataMgr.getPlayerUser().leave()
                    }.bind(this),
                    function () {
                        if(cbCancel) cbCancel()
                        cc.gg.toastMgr.removeDialog()
                    }
                )
            }else {
                if(cbDirecotory) cbDirecotory()
                cc.gg.dataMgr.getPlayerUser().leave()
            }
        }else if(nowRoom instanceof PoolRoom){
            if(!cc.gg.gameDataUtil.resultJustNow || inGame){
                let title = LanguageMng.getSentence(3)
                let positiveStr = LanguageMng.getSentence(57)   //Yes
                let passiveStr = LanguageMng.getSentence(179)   //Cancel
                let content = LanguageMng.getSentence(185)  //are u sure to back to lobby?you will lose the game
                // if(cc.gg.gameDataUtil.resultJustNow){
                //     content = LanguageMng.getSentence(184)  //are u sure to back to lobby
                // }
                cc.gg.toastMgr.showDialog(title,positiveStr,passiveStr,content,
                    function () {
                        if(cbYes) cbYes()
                        cc.gg.dataMgr.getPlayerUser().leave()
                    }.bind(this),
                    function () {
                        if(cbCancel) cbCancel()
                        cc.gg.toastMgr.removeDialog()
                    }
                )
            }else {
                if(cbDirecotory) cbDirecotory()
                cc.gg.dataMgr.getPlayerUser().leave()
            }
        }else if(nowRoom instanceof DealRoom){
            if(!cc.gg.gameDataUtil.resultJustNow || inGame){
                let title = LanguageMng.getSentence(3)
                let positiveStr = LanguageMng.getSentence(57)   //Yes
                let passiveStr = LanguageMng.getSentence(179)   //Cancel
                let content = LanguageMng.getSentence(185)  //are u sure to back to lobby?you will lose the game
                // if(cc.gg.gameDataUtil.resultJustNow){
                //     content = LanguageMng.getSentence(184)  //are u sure to back to lobby
                // }
                cc.gg.toastMgr.showDialog(title,positiveStr,passiveStr,content,
                    function () {
                        if(cbYes) cbYes()
                        cc.gg.dataMgr.getPlayerUser().leave()
                    }.bind(this),
                    function () {
                        if(cbCancel) cbCancel()
                        cc.gg.toastMgr.removeDialog()
                    }
                )
            }else {
                if(cbDirecotory) cbDirecotory()
                cc.gg.dataMgr.getPlayerUser().leave()
            }
        }else {
            cc.error("Unknown room type:",nowRoom.en_class())
        }
    },

    _onOptBtnDrop:function () {
        let title = LanguageMngTs.getSentence(3)
        let positiveStr = LanguageMngTs.getSentence(97)   //Drop
        let passiveStr = LanguageMngTs.getSentence(179)   //Cancel
        let contentStr = LanguageMngTs.getSentence(315) //"Do you want to drop?"
        cc.gg.toastMgr.showDialog(title,positiveStr,passiveStr,contentStr,
            function () {
                cc.gg.toastMgr.removeDialog()
                cc.gg.dataMgr.getPlayerUser().drop()
                this.changeOptionState(cc.gg.enumConfig.OptionState.WAIT)
                this.uiMgr._onUIShowDragBlocker(true)
            }.bind(this),
            function () {
                cc.gg.toastMgr.removeDialog()
            }
        )
    },

    showHandPokerMask:function (show) {
        this.uiMgr._onUIShowDragBlocker(show)
    },

    // _onWSClosed:function () {
    //     cc.gg.dataMgr.clearData()
    //
    //     cc.log("判断是否要重连：",!cc.gg.dataMgr.noNeedToReconnect)
    //     if(!cc.gg.dataMgr.noNeedToReconnect){
    //         cc.gg.gameDataUtil.refreshPlayerInfo(function (result) {
    //             cc.gg.dataMgr.setPlayerInfo(result.data)
    //             let playerUser = cc.gg.dataMgr.getPlayerInfo()
    //             if(playerUser.has_room){
    //                 cc.log("ws断开且玩家拥有房间，重连！")
    //                 this._onStartReconnecting()
    //             }else {
    //                 cc.log("ws断开且玩家没有房间，回到大厅")
    //                 cc.gg.gameDataUtil.goToLobby(true)
    //             }
    //         }.bind(this))
    //     }
    // },

    startDiscardFlowPassive:function (pokerValue) {
        this.onUsDiscardSuccess()
        pokerValue = parseInt(pokerValue)

        if(this.playCard && this.playCard.poker !== pokerValue){
            cc.log("服务端让出的牌与玩家要出的牌不是一张，玩家：",this.playCard.poker,"  服务端：",pokerValue)
            cc.gg.handPokerMgr.returnWaitDiscardNode()
        }else {
            cc.gg.handPokerMgr.setWaitDiscardNode(null)
        }

        if(!this.playCard || this.playCard.poker !== pokerValue){
            cc.logfl("要出的牌丢失，或要出的牌不是服务端让出的牌，弄一张服务端让出的牌")
            let objs = cc.gg.dataMgr.getPlayerUser().cardObjs
            let rdmPoker = null
            for(let i=0;i<objs.length;i++){
                let pokerObj = objs[i]
                if(pokerObj.poker === pokerValue){
                    rdmPoker = pokerObj
                    break
                }
            }
            if(!rdmPoker){
                cc.error("在本地手牌中找不到手牌：",pokerValue)
                return
            }

            cc.warn("由于客户端丢失了最后抓牌的信息，取随机一张相同的牌丢弃")
            this.setPlayCard(rdmPoker)
        }

        if(this.playCard.poker !== pokerValue){
            cc.error("handcarderror:Client play card is different with server card,local:",this.playCard,"  ",pokerValue)
            return
        }

        this._stopHandPokerDragging()
        this.changeOptionState(cc.gg.enumConfig.OptionState.WAIT)

        let pokerNode = this._getPokerNodeByPokerId(this.playCard.id)
        if(!pokerNode){
            cc.warn("No poker node with obj:",this.playCard)
            pokerNode = this.getPokerNodeByPokerValue(pokerValue)
        }

        let discardId = pokerNode.poker.id
        cc.gg.gameDataUtil.removeHandPokerObj(cc.gg.dataMgr.getPlayerUser().cardObjs,discardId)

        this.setPlayCard(null)
        cc.log("播放弃牌",pokerNode)
        this.discardPoker(pokerNode)

        let handCards = cc.gg.tpgMgr.getCommitArr(cc.gg.tpgMgr.pokerBottoms,null)
        cc.gg.dataMgr.getPlayerUser().sync(handCards)
    },

    //destroy unused bottom and its node
    clearBottoms:function () {
        for(let i=0;i<this.pokerBottoms.length;i++){
            let botObj = this.pokerBottoms[i]
            let group = botObj.pokers
            if(!group.length){
                this.pokerBottoms.splice(i--,1)
                let botNode = this._getBottomNodeByBotObj(botObj)
                if(botNode){
                    botNode.destroy()
                }
            }
        }
    },

    _stopHandPokerDragging:function () {
        let pokerNodes = this.handPokerParent.children
        for(let i=0;i<pokerNodes.length;i++){
            pokerNodes[i].getComponent("PokerModelTs").stopDraging()
        }
    },

    _onOptBtnDiscard:function () {
        if(cc.gg.handPokerMgr.selectedEndPokerNodeArray.length > 1){
            console.warn("There are more than one card selected,logic error!")
            return
        }
        this.startDiscardFlow(cc.gg.handPokerMgr.selectedEndPokerNodeArray[0])
    },

    _onOptBtnFinish:function (dragNode) {
        let title = LanguageMng.getSentence(3)
        let positiveStr = LanguageMng.getSentence(57)
        let passiveStr = LanguageMng.getSentence(56)
        let contentStr = LanguageMng.getSentence(134)
        cc.gg.toastMgr.showDialog(title,positiveStr,passiveStr,contentStr,
            function () {
                cc.gg.toastMgr.removeDialog()
                cc.gg.dataMgr.pokerCanClick = true
                this.doFinish(dragNode)
            }.bind(this),
            function () {
                cc.gg.toastMgr.removeDialog()
                this._dragFinishFail(dragNode)
            }.bind(this)
        )
    },

    _onOptBtnGroup:function () {
        cc.gg.dataMgr.pokerCanClick = true
        let selectingPokerNodes = cc.gg.handPokerMgr.selectedEndPokerNodeArray
        cc.gg.emitEvent("option_group",selectingPokerNodes)

        if(this.gameState === cc.gg.enumConfig.OptionState.GROUP){
            let handCards = this.getCommitArr(this.pokerBottoms,null)
            cc.gg.dataMgr.getPlayerUser().sync(handCards)
        }

        for(let i=0;i<selectingPokerNodes.length;i++){
            selectingPokerNodes[i].getComponent("PokerModelTs").cancelSelected()
            selectingPokerNodes.splice(i--,1)
        }
        this.uiMgr._onUIShowBtnGroup(false)
        cc.gg.emitEvent("start_group")
        cc.gg.emitEvent("update_bottoms_width")
        // this.scheduleOnce(function () {
        //     for(let i=0;i<selectingPokerNodes.length;i++){
        //         selectingPokerNodes[i].getComponent("PokerModelTs").cancelSelected()
        //         selectingPokerNodes.splice(i--,1)
        //     }
        //     this.uiMgrNode.emit("ui_show_btn_group",false)
        //     cc.gg.emitEvent("start_group")
        //     cc.gg.emitEvent("update_bottoms_width")
        // }, 0)
    },

    _onGameInitUserScore:function () {
        // for(let i in cc.gg.dataMgr.users){
        //     if(cc.gg.dataMgr.room instanceof DealRoom){
        //         cc.gg.dataMgr.users[i].score = cc.gg.dataMgr.room.info.r_top * 80
        //         cc.log("初始化分数为：",cc.gg.dataMgr.room.info.r_top * 80)
        //     }else {
        //         cc.gg.dataMgr.users[i].score = 0
        //     }
        // }

        this.uiMgrNode.emit("ui_update_seat_pts")
    },

    _onUserLeave:function (id) {
        if(id === cc.gg.dataMgr.getPlayerGameId()){

        }else {
            this.uiMgrNode.emit("ui_user_leave",id)
        }
    },

    _onUserDestroy:function (id) {
        if(id === cc.gg.dataMgr.getPlayerGameId()){

        }else {
            cc.log("尝试清空User：",id)
            for(let i in cc.gg.dataMgr.users){
                let user = cc.gg.dataMgr.users[i]
                if(user.id === id){
                    cc.log("清空User：",id)
                    let idx = cc.gg.dataMgr.users.indexOf(user)
                    cc.gg.dataMgr.users.splice(idx,1)
                    break
                }
            }
            this.uiMgrNode.emit("ui_user_destroy",id)
        }
    },

    _onFlowShuffle:function () {
        let array = []
        let move = cc.moveTo(0.2,cc.v2(0,0))
        array.push(move)
        let func = cc.callFunc(function () {

            cc.loader.loadRes("anim/shuffle",cc.Prefab,function (err, prefab) {
                let newShuffle = cc.instantiate(prefab)
                newShuffle.name = "shuffle"
                this.pokerStackNode.parent.addChild(newShuffle)
                this.pokerStackNode.opacity = 0

                cc.loader.releaseRes("anim/shuffle")
            }.bind(this))

            cc.gg.dataMgr.room.clearDiscards()
            cc.gg.disCardMgr.updateDiscardStack(cc.gg.dataMgr.room.getDicards(cc.gg.disCardMgr.stackShowCount))
        }.bind(this),this)
        array.push(func)

        let shuffleDelay= cc.delayTime(1.5)
        array.push(shuffleDelay)

        let func2 = cc.callFunc(function () {
            this.pokerStackNode.opacity = 255
            let shuffleNode = cc.find("shuffle",this.pokerStackNode.parent)
            if(shuffleNode) shuffleNode.destroy()
        }.bind(this),this)
        array.push(func2)

        let worldPos2 = cc.gg.baseUtil.getWorldPos(this.pokerStackGamePos)
        let botCardTarPos = this.pokerStackNode.parent.convertToNodeSpaceAR(worldPos2)
        let move2= cc.moveTo(0.2,botCardTarPos)
        array.push(move2)

        let seq = cc.sequence(array)
        this.pokerStackNode.runAction(seq)
    },

    showPokerStack:function (show) {
        if(!this.pokerStackNode){
            console.log("场景已销毁，停止pokerStackNode")
            return
        }
        if(show){
            this.pokerStackNode.opacity = 255
        }else {
            this.pokerStackNode.opacity = 0
        }
    },

    update (dt) {
        //time
        if (cc.gg.dataMgr.room && cc.gg.dataMgr.room.timer_cd > 0) {
            cc.gg.dataMgr.room.timer_cd = Math.max(0, cc.gg.dataMgr.room.timer_cd - dt);
            this._updateTimerCd(cc.gg.dataMgr.room.timer_cd)
            this._updateCommittingCount(cc.gg.dataMgr.room.timer_cd)
        }

        //hand poker mask
        this._updateHandPokerMask(dt)
    },

    // _updateHandPokerMask:function (dt) {
    //     let playerUser = cc.gg.dataMgr.getPlayerUser()
    //     if(cc.gg.dataMgr.room && cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.IN_GAME
    //         && playerUser && playerUser.b_state === cc.gg.enumConfig.ReadyState.ELIMINATED){
    //         this.showHandPokerMask(true)
    //     }else {
    //         this.showHandPokerMask(false)
    //     }
    // },

    _updateHandPokerMask:function (dt) {
        let playerUser = cc.gg.dataMgr.getPlayerUser()
        if(cc.gg.dataMgr.room && cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.IN_GAME
            && playerUser && (playerUser.b_state === cc.gg.enumConfig.ReadyState.ELIMINATED || playerUser.b_state === cc.gg.enumConfig.ReadyState.DROPED)){
            this.showHandPokerMask(true)
        }else {
            this.showHandPokerMask(false)
        }
    },


    _updateCommittingCount:function (timercd) {

        if (cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.COMMITTING) {
            let countUsers = this.getCommittingUsers()
            for(let i=0;i<countUsers.length;i++){
                let user = countUsers[i]
                let seatNode = this.getSeatByUID(user.id)
                if(!seatNode){



                    cc.log("adsfasd")
                    console.log("在刚开始commit的阶段有这个用户但现在没有了",user.id)
                    continue
                }
                let script = seatNode.getComponent("SeatOther")
                if(!script){
                    script = seatNode.getComponent("TPPHead")
                }
                script.updateCountting(timercd)
            }
        }
    },

    _updateTimerCd:function (timercd) {
        // if (cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.IDLE) {
        //     //等待倒计时
        //     this.uiMgr._onGameCountDownStart(cc.gg.dataMgr.room)
        // }
        if (cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.IN_GAME) {
            if(!this._animDispatching){
                let avartarScript = this.getActiveSeatScript()
                if(avartarScript) avartarScript.updateCountting(timercd)
            }
        }

        // if (cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.GAMEINTERVAL) {
        //     let avartarScript = this.getActiveSeatScript()
        //     if(avartarScript) avartarScript.updateCountting(cc.gg.dataMgr.room.timer_cd)
        // }
    },

    _onDealInfoCountDownFinish:function () {
        // cc.gg.dataMgr.room instanceof PointRoom
        // cc.log("尝试发送ready",cc.gg.dataMgr.room.state)
        // if((cc.gg.dataMgr.room.state === 5 || cc.gg.dataMgr.room.state === 3 || cc.gg.dataMgr.room.state === 0) && cc.gg.tpgMgr.someOneFinish)
        //     cc.gg.dataMgr.getPlayerUser().ready()

        // if(cc.gg.gameDataUtil.resultJustNow && cc.gg.dataMgr.room instanceof PointRoom){
        //     cc.gg.dataMgr.getPlayerUser().ready()
        //     cc.log("刚发了result，是point房间")
        // }

        let room = cc.gg.dataMgr.room
        if(room instanceof PointRoom){
            cc.log("Points房间，直接发送ready")
            cc.gg.dataMgr.getPlayerUser().ready()
        }else if(room instanceof PoolRoom){
            cc.log("Pool，直接发送ready")
            cc.gg.dataMgr.getPlayerUser().ready()
        }else if(room instanceof DealRoom){
            cc.log("Deal房间，直接发送ready")
            cc.gg.dataMgr.getPlayerUser().ready()
        }else {
            cc.error("未知的房间类型！")
        }
    },

    setActiveAvatar:function (avartar) {
        this.activeAvartar = avartar
    },

    getActiveAvatar:function () {
        return this.activeAvartar
    },

    getActiveSeatScript:function () {
        let activeAvatar = this.getActiveAvatar()
        if(!activeAvatar) return null

        for(let i=0;i<this.opponentSeatParent.children.length;i++){
            let otherSeatScript = this.opponentSeatParent.children[i].getComponent("SeatOther")
            if(otherSeatScript.isUser(activeAvatar)){
                return otherSeatScript
            }
        }

        if(activeAvatar === cc.gg.dataMgr.getPlayerUser()){
            return this.playerSeat.getComponent("TPPHead")
        }


        cc.warn("Can't find seat by user:",activeAvatar)
        return null
    },

    // _onStartReconnecting:function () {
    //     this._stopReconnecting()
    //
    //     this._doReconnect()
    //     // this._reconnectTimes = 1
    //     // this.reconnectCb = function (dt) {
    //     //     this._doReconnect()
    //     //     if(this._reconnectTimes++ === 5){function
    //     //         cc.find("Canvas/UIManager").emit("ui_show_reconnect_button",true)
    //     //     },
    //     // }
    //     // this.schedule(this.reconnectCb.bind(this), 2, 4)
    // },

    _onUIUpdateHeadScore:function (id,newScore) {
        let seatNode = this.getSeatByUID(id)
        if(!seatNode){
            cc.warn("找不到uid为",id,"的座位")
            return
        }

        let script = null
        if(id === cc.gg.dataMgr.getPlayerGameId()){
            script = seatNode.getComponent("TPPHead")
        }else {
            script = seatNode.getComponent("SeatOther")
        }
        script.updateGameScore(newScore)
    },

    _onFlowCalculating:function () {
        this.uiMgrNode.emit("ui_show_drag_blocker",false)
        cc.find("UIManager",this.node).emit("ui_show_view_node",true)
    },

    onOptionSelectNode:function (pokerNodeArray) {
        if(pokerNodeArray.length > 1){
            this.uiMgrNode.emit("ui_show_btn_group",true)
        }else {
            this.uiMgrNode.emit("ui_show_btn_group",false)
        }

        if(pokerNodeArray.length === 1 && this.gameState === cc.gg.enumConfig.OptionState.PLAY){
            this.uiMgrNode.emit("ui_show_btn_discard",true)
        }else {
            this.uiMgrNode.emit("ui_show_btn_discard",false)
        }
    },

    onStartGame:function (cards, mixCard, bottomCard) {
        this.uiMgrNode.emit("ui_hide_deal_waitting_string")

        if(!cards){
            cc.log("此人没有被发牌：",cards)
            return
        }

        cc.log("发牌1111：",cards)
        this.someOneFinish = false
        cc.gg.dataMgr.noNeedToReconnect = false

        this.initTable()
        if(cards && cards.length){
            this.dispatchPokers(cards)
        }else {
            this.animOpenDeck(
                cc.gg.dataMgr.room.c_open_objs[0],
                cc.gg.dataMgr.getMixCard()
            )
        }
    },

    onTestDispatchPokers:function () {

        // let oriCards = [
        //     1,2,3,4,5,6,7,8,9,10,11,12,13
        // ]
        //
        // this.initTable()
        // cc.gg.dataMgr.getPlayerUser().cardObjs = cc.gg.dataMgr.convertToClientPokerObj(oriCards)
        // this.dispatchPokers(cc.gg.dataMgr.getPlayerUser().cardObjs)
    },

    onGameRoomDestroy:function () {
        // cc.logfl("基类：房间被销毁，不用重连回来了")
        cc.gg.dataMgr.noNeedToReconnect = true
        cc.gg.gameDataUtil.goToLobby(true)
    },

    // _setPokersInDispatching(playerHandPokers){
    //     for(let i=0;i<playerHandPokers.length;i++){
    //         let node = playerHandPokers[i]
    //         let pokerModelScript = node.getComponent("PokerModelTs")
    //         pokerModelScript.inDispatchAnim = true
    //     }
    // },

    dispatchPokers:function (playerHandPokers) {
        let worldPos = this.pokerStackNode.parent.convertToWorldSpaceAR(this.pokerStackNode.position)
        let doriPos = this.handPokerParent.convertToNodeSpaceAR(worldPos)

        //dispatch down seat pokers
        this._handPokerFlyCountAlready = 0
        this._handPokerFlyCount = playerHandPokers.length
        let deckWorldY = cc.gg.tpgMgr.pokerStackNode.parent.convertToWorldSpaceAR(cc.gg.tpgMgr.pokerStackNode.position).y
        let handWorldY = cc.gg.tpgMgr.handPokerParent.parent.convertToWorldSpaceAR(cc.gg.tpgMgr.handPokerParent.position).y
        let self = this

        // this._setPokersInDispatching(playerHandPokers)

        for(let i=0;i<playerHandPokers.length;i++){

            let dispatchDelay = cc.delayTime(0.04*i+0.2)
            let addPoker = cc.callFunc(function () {
                if(!cc.gg.dataMgr.room && !cc.gg.dataMgr.playGuild){
                    cc.warn("由于room被销毁，动画终止1")
                    return
                }

                let newPoker = cc.instantiate(this.pokerModel)
                this.handPokerParent.addChild(newPoker)
                newPoker.position = doriPos

                let pokerObj = playerHandPokers[i]
                newPoker.poker = pokerObj

                let modelScript = newPoker.getComponent("PokerModelTs")
                // let pokerModelScript = newPoker.getComponent("PokerModelTs")
                modelScript.inDispatchAnim = true

                let moveToTargetPos = cc.moveTo(0.16,this.playerPokerPoses[i])

                let flipDelay = cc.delayTime(0.1)
                let scaleToShow = cc.scaleTo(0.2, 0, 1.6)

                let showRes = cc.callFunc(function () {
                    if(!cc.gg.dataMgr.room && !cc.gg.dataMgr.playGuild){
                        cc.warn("由于room被销毁，动画终止1")
                        return
                    }
                    modelScript.initPoker(this,handWorldY,deckWorldY)
                }.bind(newPoker.poker),this)
                let scaleToItem = cc.scaleTo(0.2, 1.0, 1.0)
                let countFly = cc.callFunc(function () {
                    // cc.gg.emitEvent("anim_hand_pokers_fly")
                    self._onHandPokerFly()
                }.bind(this),this)
                let callfunc = cc.sequence(flipDelay,scaleToShow,showRes,scaleToItem,countFly)

                this.soundMgrNode.getComponent("SoundManager").playPokerFlySound()
                let seq = cc.spawn(moveToTargetPos,callfunc)
                newPoker.runAction(seq)

            }.bind(this),this)

            this.node.runAction(cc.sequence(dispatchDelay,addPoker))
        }
    },

    onPlayerTurnStart:function (id, countDownTime, isReconnect) {
        let activeAvatar = cc.gg.dataMgr.getUser(id)
        if(!cc.gg.dataMgr.playGuild){
            console.assert(activeAvatar)
        }
        cc.gg.tpgMgr.setActiveAvatar(activeAvatar)

        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(!this._animDispatching){
                if(!id){
                    return true
                }

                let userExsists = false
                for(let x in cc.gg.dataMgr.users){
                    let tuid = cc.gg.dataMgr.users[x].id
                    if(tuid === id){
                        userExsists = true
                        break
                    }
                }
                //all users are changed,may the last game has been finished...
                //It may be happened when game back to front,the message enter instantial
                //当玩家从后台回到游戏，服务端消息会快速涌入，这将造成这个函数执行之后，马上这个玩家可能已经退出房间了
                //(这在隔一局回来的时候会发生)
                if(!userExsists)
                    return true


                this._doTurnStart(id,countDownTime,isReconnect)
                return true
            }
            return false
        }.bind(this))
    },

    _doTurnStart:function (userId, countDownTime, isReconnect) {
        let id = parseInt(userId)
        countDownTime = parseInt(countDownTime)

        for(let i=0;i<this.opponentSeatParent.children.length;i++)
            this.opponentSeatParent.children[i].getComponent("SeatOther").stopCountting()
        // let seatScript = null
        if(id === cc.gg.dataMgr.getPlayerGameId()){
            cc.find("Canvas/SoundManager").getComponent("SoundManager").playTurnNoticeVibration()
            // seatScript = this.playerSeat.getComponent("TPPHead")

            let handCards = cc.gg.dataMgr.playGuild ? cc.gg.dataMgr.guildData.cards : cc.gg.dataMgr.getPlayerUser().cardObjs
            cc.log("check hand cards：",handCards)
            if(handCards.length === 13){
                //need grab
                let canNotBlink = false
                if(this._animDispatching){
                    canNotBlink = true
                }
                this.changeOptionState(cc.gg.enumConfig.OptionState.GRAB)
                if(canNotBlink){
                    this.pokerStackBlinkStop()
                    this.deckBlinking = true
                }
            }else {
                if(isReconnect){
                    this.changeOptionState(cc.gg.enumConfig.OptionState.PLAY)
                }else {
                    cc.error("轮到本玩家，但本玩家本地手牌不是13张，逻辑错误！")
                    console.log("由于不可知的逻辑错误，客户端主动断开连接以便重连刷新。定位：1")
                    // cc.gg.dataMgr.clearData()
                    // GameWS.disconnect()
                    return
                }
            }
        }else if(cc.gg.dataMgr.playGuild){
            // seatScript = this.opponentSeatParent.children[0].getComponent("SeatOther")
            this.changeOptionState(cc.gg.enumConfig.OptionState.WAIT)
            this.playerSeat.getComponent("TPPHead").stopCountting()
        }else {
            // seatScript = this.getSeatByUID(id).getComponent("SeatOther")
            this.changeOptionState(cc.gg.enumConfig.OptionState.WAIT)
            this.playerSeat.getComponent("TPPHead").stopCountting()
        }

        // seatScript.startCountting(countDownTime)
    },

    async startDiscardFlow (discardPokerNode) {
        if(!discardPokerNode){
            cc.warn("You have not select any poker! 1")
            return
        }

        if(!cc.gg.dataMgr.playGuild && !cc.gg.tpgMgr.canDiscard){
            cc.log("当前阶段不能出牌canDiscard:",cc.gg.tpgMgr.canDiscard)
            return
        }

        cc.gg.handPokerMgr.setWaitDiscardNode(discardPokerNode)
        this.setPlayCard(discardPokerNode.poker)

        let serverPoker = cc.gg.dataMgr.convToServerPokerValue(discardPokerNode.poker.poker)
        if(cc.gg.dataMgr.playGuild){
            this.discardPoker(discardPokerNode)
        }else{
            let code = await cc.gg.dataMgr.getPlayerUser().discard(serverPoker)
            if(code === 0){
                this.onUsDiscardSuccess()
            }
        }

        this.changeOptionState(cc.gg.enumConfig.OptionState.WAIT)
    },
    ///////////////////////////////////////////////////////////////////
    onUsDiscardSuccess(){
        this.uiMgr.showDisStackNotice(false,null)
    },

    _refreshTableUnderReconnecting:function () {
        let playerUser = cc.gg.dataMgr.getPlayerUser()
        let roomState = cc.gg.dataMgr.room.state
        let mixCard = cc.gg.dataMgr.getMixCard()

        cc.logfl("恢复游戏状态")
        cc.gg.gameDataUtil.gameStarted = true
        cc.gg.dataMgr.isReconnect = false
        this.uiMgr.showBtnReady(false)

        if((roomState === cc.gg.enumConfig.RoomNetState.IN_GAME || roomState === cc.gg.enumConfig.RoomNetState.COMMITTING) && !this.handPokerParent.children.length && playerUser.cards){
            this.resetHandPokers(playerUser)
        }

        cc.log("s_cards:",playerUser.s_cards)
        if(!cc.gg.baseUtil.isArrayValid(playerUser.s_cards)){
            this.initHandCardBottomsWithMixCard(cc.gg.dataMgr.getPlayerHandCardObjs(),mixCard)
        }else{
            cc.log("s_cards_objs:",playerUser.s_cards_objs)
            this._initHandCardBottomWithRestoreArray(playerUser.s_cards_objs)
        }

        if(cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.IN_GAME ||
            cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.COMMITTING){
            this.restoreHandPokers()
        }


        if(cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.IN_GAME){
            this.restoreOpenDeck(cc.gg.dataMgr.room.getDicards(cc.gg.disCardMgr.stackShowCount),cc.gg.dataMgr.getMixCard())
        }

        if(cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.COMMITTING && cc.gg.dataMgr.getPlayerUser().b_state === cc.gg.enumConfig.ReadyState.COMMITED){
            this.uiMgrNode.emit("ui_show_view_node",true)
            cc.warn("在这里处理结算板的恢复，服务端还没数据")
        }
        else this.uiMgrNode.emit("ui_show_view_node",false)

        cc.gg.tpgMgr.canDragHandPokers = true

        if(playerUser.b_state === 4){
            this.uiMgrNode.emit("ui_show_drag_blocker",true)
        }else {
            this.uiMgrNode.emit("ui_show_drag_blocker",false)
        }
        //////

        //update empty seats
        this._initEmptySeats()
        this.playerSeat.getComponent("TPPHead").initSeatState(playerUser?playerUser.b_state:null)

        //fill seats with user
        this._fillSeats(cc.gg.dataMgr.users)

        if(cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.COMMITTING){
            if(playerUser.b_state !== cc.gg.enumConfig.ReadyState.DROPED &&
                playerUser.b_state !== cc.gg.enumConfig.ReadyState.ELIMINATED &&
                playerUser.b_state !== cc.gg.enumConfig.ReadyState.COMMITED){
                this.uiMgrNode.emit("ui_show_btn_declare",true)
                this.addCommittingUser(playerUser)
            }
        }

        if(cc.gg.dataMgr.room.state === cc.gg.enumConfig.RoomNetState.IN_GAME){
            this.node.emit("flow_player_turn",cc.gg.dataMgr.room.c_id,cc.gg.dataMgr.room.timer_cd,true)
            let sevSeqObj = cc.gg.dataMgr.room.comps
            if(!sevSeqObj){
                cc.error("Room has no attr :comps!")
            }else{
                // this.updateSeatSequence(sevSeqObj)
                cc.find("Canvas").emit("msgwatcher_add",function () {
                    if(cc.gg.baseUtil.getMapLength(cc.gg.dataMgr.users) === sevSeqObj.length){
                        this.updateDIndicator(sevSeqObj)
                        return true
                    }
                    return false
                }.bind(this))
            }
        }

        this.updateTopBar()
        let showDealBoardBtn = !cc.gg.dataMgr.playGuild && (cc.gg.dataMgr.room instanceof PoolRoom || cc.gg.dataMgr.room instanceof DealRoom)
        this.uiMgr._onUIShowBtnDeal(showDealBoardBtn)


        // if(playerUser.b_state === cc.gg.enumConfig.ReadyState.ELIMINATED){
        //     cc.gg.tpgMgr.showHandPokerMask(true)
        // }

        this.scheduleOnce(function () {
            cc.gg.dataMgr.getPlayerUser().ready()
        },0)
    },


    _initEmptySeats:function () {
        for(let i=0;i<this.opponentSeatParent.children.length;i++){
            let seatNode = this.opponentSeatParent.children[i]
            seatNode.getComponent("SeatOther").initSeat(null)
        }
    },

    _fillSeats:function (users) {
        users.forEach(userEntiry => {
            // userEntiry.score = cc.gg.dataMgr.room.getTotalScore(userEntiry.id)
            cc.log("PTS:",userEntiry.id,"   ",userEntiry.score)
            this.uiMgr._onUpdateSeatUser(userEntiry,true)
            // cc.find("Canvas/UIManager").emit("ui_init_seat_user",userEntiry,true)
        })
    },

    resetHandPokers:function (playerUser) {
        let worldPos = this.pokerStackNode.parent.convertToWorldSpaceAR(this.pokerStackNode.position)
        let doriPos = this.handPokerParent.convertToNodeSpaceAR(worldPos)

        let realCards = cc.gg.gameDataUtil.getRealRestoreCards(playerUser.s_cards,playerUser.cards)
        cc.logfl("手里真正的牌是：",realCards)
        playerUser.setSCardsObjs(this.getRestoreCards(realCards))
        cc.logfl("要恢复的牌是：",playerUser.s_cards_objs)
        playerUser.cardObjs = cc.gg.gameDataUtil.convertPokerObjGroupToArray(playerUser.s_cards_objs)//cc.gg.dataMgr.convertToClientPokerObj(playerUser.cards)
        this._syncResCardsAndCards(playerUser.s_cards_objs,playerUser.cards)
        cc.logfl("回复到手里真正的牌是：",playerUser.s_cards_objs)

        let deckWorldY = cc.gg.tpgMgr.pokerStackNode.parent.convertToWorldSpaceAR(cc.gg.tpgMgr.pokerStackNode.position).y
        let handWorldY = cc.gg.tpgMgr.handPokerParent.parent.convertToWorldSpaceAR(cc.gg.tpgMgr.handPokerParent.position).y

        if(cc.gg.baseUtil.isArrayValid(playerUser.s_cards_objs)){
            let handCards = playerUser.s_cards_objs
            for(let i=0;i<handCards.length;i++){
                for(let j=0;j<handCards[i].length;j++){
                    let newPoker = cc.instantiate(this.pokerModel)
                    this.handPokerParent.addChild(newPoker)
                    newPoker.position = doriPos

                    let pokerObj = handCards[i][j]
                    newPoker.poker = pokerObj
                    newPoker.getComponent("PokerModelTs").initPoker(pokerObj,handWorldY,deckWorldY)
                }
            }
        }else {
            let handCards = playerUser.cardObjs
            for(let i=0;i<handCards.length;i++){
                let newPoker = cc.instantiate(this.pokerModel)
                this.handPokerParent.addChild(newPoker)
                newPoker.position = doriPos

                let pokerObj = handCards[i]
                newPoker.poker = pokerObj
                newPoker.getComponent("PokerModelTs").initPoker(pokerObj,handWorldY,deckWorldY)
            }
        }
    },

    restoreHandPokers:function (restoreCardsArray) {
        // let mixCard = cc.gg.dataMgr.getMixCard().poker

        this.initRestorePokerBottoms()
        cc.gg.emitEvent("update_bottoms_width")
    },

    /**
     *
     * @param seatNodes my seat must be the first element
     * @param seqArray  my user-info must be the first element
     */
    updateSeatSequence:function (seqArray) {
        let seatNodes = []
        seatNodes.push(this.playerSeat)
        for(let i=this.opponentSeatParent.children.length-1;i>=0;i--){
            let n = this.opponentSeatParent.children[i]
            let haveUser = n.getComponent("UserSeat").playerInfo ? true : false
            n.getComponent("UserSeat").initSeat(null)
            if(haveUser)
                seatNodes.push(n)
        }
        cc.log("所有座位的数组：",seatNodes)

        let clientSeqArray = this._arrangeServerUserSeq(seqArray)
        cc.log("接下来按照这个顺序排列：",clientSeqArray)


        for(let i=0;i<seatNodes.length;i++){
            let userInfo = clientSeqArray[i]
            if(!userInfo){
                cc.log("updateSeatSequence:no user info at index:",i)
                return
            }

            let seatScript = seatNodes[i].getComponent("SeatOther")
            if(seatScript){
                seatScript.initSeat(userInfo)
            }else {
                seatScript = seatNodes[i].getComponent("TPPHead")
                seatScript.initTPPHead(userInfo)
            }
        }
        // this._arrangeServerUserSeat(seatNodes)

        // if(isReconenct){
        //     return 0
        // }
        //
        // return this._showCompare(seqArray)
    },

    updateDIndicator:function (seqArray) {
        let seatNodes = []
        seatNodes.push(this.playerSeat)
        for(let i=this.opponentSeatParent.children.length-1;i>=0;i--){
            seatNodes.push(this.opponentSeatParent.children[i])
        }

        let clientSeqArray = this._arrangeServerUserSeq(seqArray)
        let firstId = this.getFirstId(clientSeqArray)
        let testUserObj = cc.gg.dataMgr.getUser(firstId)
        cc.log("==============D是ID为：",firstId,"的玩家",testUserObj.name)

        for(let i=0;i<seatNodes.length;i++){

            let seatScript = seatNodes[i].getComponent("SeatOther")
            if(!seatScript){
                seatScript = seatNodes[i].getComponent("TPPHead")
            }
            let userInfo = seatScript.playerInfo
            if(!userInfo) continue

            //show first user indicator(D icon)
            if(userInfo.id === firstId){
                // cc.log("+++++++++++++++++++++玩家显示D")
                seatScript.showIndicatorFirstSeat(true)
            }else {
                seatScript.showIndicatorFirstSeat(false)
            }
        }
    },

    getFirstId:function (clientSeqArray) {

        let fuid = cc.gg.dataMgr.room.f_id
        cc.log("====这一局出牌玩家是：",fuid)
        let aliveUsers = []

        cc.log("====111",clientSeqArray)
        for(let i=0;i<clientSeqArray.length;i++){
            let userObj = clientSeqArray[i]
            cc.log("====userObj",userObj)
            if(userObj.b_state !== cc.gg.enumConfig.ReadyState.ELIMINATED){
                aliveUsers.push(userObj)
            }
        }
        cc.log("====aliveUsers",aliveUsers)

        let lastUser = null
        cc.log("还有",aliveUsers.length,"个存活玩家")
        for(let i=0;i<aliveUsers.length;i++){
            let userObj = aliveUsers[i]
            if(fuid === userObj.id){
                if(!lastUser){
                    cc.log("没有上一个玩家呢还，返回队列最后一个玩家",aliveUsers[aliveUsers.length-1].id)
                    return aliveUsers[aliveUsers.length-1].id
                }
                cc.log("返回上一个玩家",lastUser.id)
                return  lastUser.id
            }
            lastUser = userObj
        }

        cc.error("没有找到D！！！！！！")
        return null
    },

    _getComparePokerById(userId){
        for(let i=0;i<this.compareParent.children.length;i++){
            let node = this.compareParent.children[i]
            let comPoker = node.getComponent("compare_poker")
            if(comPoker.getSeatUserId() === userId){
                return comPoker
            }
        }
        return null;
    },
    /**
     *
     * @param seq 已经排好序的，本机玩家在0位置
     * @private
     */
    showCompare:function (seq) {
        let clientSeqArray = this._arrangeServerUserSeq(seq)
        cc.log("接下来按照这个顺序排列：",clientSeqArray)

        this.compareParent.active = true
        let comparePokers = this.compareParent.children
        for(let i=0;i<comparePokers.length;i++){
            comparePokers[i].active = false
        }

        let firstId = seq[0].id

        let seats = []
        seats.push(this.playerSeat.getComponent("UserSeat"))
        let oppSeats = this.opponentSeatParent.children
        for(let i=0;i<oppSeats.length;i++){
            let node = oppSeats[i]
            let userSeat = node.getComponent("UserSeat")
            seats.push(userSeat)
        }


        for(let i=0;i<seats.length;i++){
            let userSeat = seats[i]
            if(!userSeat.playerInfo) continue
            userSeat.comparePoker.node.active = true
            if(firstId === userSeat.playerInfo.id){
                userSeat.comparePoker.startComparePokerBorderBlink()
            }else {
                userSeat.comparePoker.stopComparePokerBorderBlink()
            }

            let card = this._getObjFromCompareSeq(userSeat.playerInfo.id,seq)
            cc.log("比牌阶段：显示点数牌：",card)
            cc.gg.resUtil.setPokerFrameSimple(userSeat.comparePoker.spriteNode.getComponent(cc.Sprite),card)
        }

        // for(let i=0;i<clientSeqArray.length;i++){
        //     let uObj = clientSeqArray[i]
        //     let comPoker = this._getComparePokerById(uObj.id)
        //     if(comPoker){
        //         comPoker.node.active = true
        //         if(firstId === uObj.id){
        //             comPoker.startComparePokerBorderBlink()
        //         }else {
        //             comPoker.stopComparePokerBorderBlink()
        //         }
        //         let card = this._getObjFromCompareSeq(uObj.id,seq)
        //         cc.log("显示点数牌：",card)
        //         cc.gg.resUtil.setPokerFrameSimple(comPoker.spriteNode.getComponent(cc.Sprite),card)
        //     }
        // }

        // for(let i=0;i<comparePokers.length;i++){
        //     let node = comparePokers[i]
        //     let userObj = clientSeqArray[i]
        //     if(!userObj){
        //         node.active = false
        //         continue
        //     }
        //
        //     node.active = true
        //     let script = node.getComponent("compare_poker")
        //     if(firstId === userObj.id){
        //         script.startComparePokerBorderBlink()
        //     }else {
        //         script.stopComparePokerBorderBlink()
        //     }
        //     let card = this._getObjFromCompareSeq(userObj.id,seq)
        //     cc.log("显示点数牌：",card)
        //     cc.gg.resUtil.setPokerFrameSimple(script.spriteNode.getComponent(cc.Sprite),card)
        // }

        let timeDelay = 4
        this.scheduleOnce(function () {
            this.compareParent.active = false
            cc.log("停止停止比牌，都隐藏=========")
            for(let i=0;i<comparePokers.length;i++){
                let node = comparePokers[i]
                node.active = false
            }
        }.bind(this), timeDelay)

        return timeDelay
    },

    _getObjFromCompareSeq:function (id,seq) {
        for(let i=0;i<seq.length;i++){
            let seqObj = seq[i]
            if(seqObj.id === id)
                return seqObj.card
        }
        cc.error("无法从比牌序列中获取对象：",id)
        return null
    },

    // _arrangeServerUserSeat:function (userSeq,userSeats) {
    //     for(let i=0;i<userSeats.length;i++){
    //
    //     }
    // },

    _arrangeServerUserSeq:function (userSeqs) {
        let infoArray = []
        let oriSeqCopy = [].concat(userSeqs)
        infoArray.push(cc.gg.dataMgr.getPlayerUser())

        let start = false
        //第一遍，从本机玩家开始push，为了保证顺序：玩家，逆1，逆2，逆3，逆4，逆5
        for(let i=0;i<oriSeqCopy.length;i++){
            let obj = oriSeqCopy[i]
            let id = parseInt(obj.id)
            let card = obj.card

            if(id == cc.gg.dataMgr.getPlayerUser().id){
                cc.log("找到了玩家！!!!!!!!!!!!!!!!!!!!!")
                start = true
                oriSeqCopy.splice(i--,1)
                continue
            }

            if(start){
                let userObj = cc.gg.dataMgr.getUser(id)
                infoArray.push(userObj)
                oriSeqCopy.splice(i--,1)
                continue
            }
        }

        //第二遍
        for(let i=0;i<oriSeqCopy.length;i++){
            let obj = oriSeqCopy[i]
            let id = obj.id
            let card = obj.card

            let userObj = cc.gg.dataMgr.getUser(id)
            infoArray.push(userObj)
            oriSeqCopy.splice(i--,1)
        }
        return infoArray
    },

    updateTopBar:function () {
        //update top bar info
        let championPrize = cc.gg.dataMgr.room.prize ? cc.gg.dataMgr.room.prize[0].coin : 0
        championPrize = championPrize ? championPrize : 0
        cc.log("championPrize:",championPrize)

        let room = cc.gg.dataMgr.room
        let bet = 0
        let roomName = ""
        if(room instanceof PoolRoom){
            bet = room.info.s_top
            roomName = "Pool-"+bet
        }else if(room instanceof DealRoom){
            bet = room.multi
            roomName = "Best of "+room.info.r_top
        }else if(room instanceof PointRoom){
            roomName = cc.gg.enumConfig.getRoomObj(cc.gg.enumConfig.RoomType.POINTS,room.mode).name
            bet = room.multi
        }else {
            cc.error("unknown room type????")
        }

        this.uiMgr.initTopInfo(room.room_id,
            roomName,
            bet)

        this.uiMgr.updateTopPrize(championPrize)

        if(room instanceof DealRoom){
            if(!room.prize || room.prize.length === 0)
                return
            let prize1 = room.prize[0].coin
            let prize2 = room.prize[1] ? room.prize[1].coin : 0
            cc.find("Canvas/UIManager").emit("ui_update_top_info_prize",prize1,prize2)
        }
    },

    opponentDiscardFinishPoker:function (id,pokerObj) {
        let seatNode = this.getSeatByUID(id)
        let worldPos = seatNode.parent.convertToWorldSpaceAR(seatNode.position)
        let nodePos = this.finishSlotNode.convertToNodeSpaceAR(worldPos)

        let newDisCard = cc.instantiate(this.disCardModel)
        newDisCard.position = nodePos
        newDisCard.getComponent("DiscardPokerModel").initDiscardPoker(pokerObj)

        this.finishSlotNode.addChild(newDisCard)

        let moveTo = cc.moveTo(0.1,cc.Vec2.ZERO)
        let callFunc = cc.callFunc(function () {
            cc.gg.emitEvent("data_finish_one",pokerObj)
        }.bind(this),this)

        newDisCard.runAction(cc.sequence(moveTo,callFunc,cc.removeSelf()))
    },

    _onReadyClicked:function (event) {
        cc.gg.dataMgr.getUser(cc.gg.dataMgr.getPlayerGameId()).ready()
    },

    _clearTable:function (optionState) {
        cc.log("=========================clear table=========================")
        this.uiMgr._onUIShowDragBlocker(false)
        // this.uiMgrNode.emit("ui_show_btn_ready",true)
        this.uiMgr._onUIShowGotoDealinfo(false)
        this.uiMgrNode.emit("ui_show_finish_indicator",false,null)
        cc.gg.emitEvent("ui_clear_finish_slot")
        // this.uiMgrNode.emit("ui_hide_score")

        this.uiMgrNode.emit("ui_show_btn_declare",false)

        this._stopAllCounting()

        this._removeAllHandPokerNodes()

        this.pokerStackNode.originPos = this.pokerStackNode.originPos || cc.Vec2.ZERO
        this.pokerStackNode.position = this.pokerStackNode.originPos
        this.bottomParent.removeAllChildren(true)
        this.pokerStackGamePos.removeAllChildren(true)
        cc.gg.disCardMgr.clearDiscardsStack()
        this.pokerStackBlinkStop()
        if(optionState){
            this.changeOptionState(optionState)
        }else
            this.changeOptionState(cc.gg.enumConfig.OptionState.DISPATCHING)
    },

    _removeAllHandPokerNodes:function () {
        let handPokers = this.handPokerParent.children
        for(let i=0;i<handPokers.length;i++){
            handPokers[i].active = false
            handPokers[i].destroy()
        }
        this.handPokerParent.removeAllChildren(true)
    },

    _stopAllCounting:function () {
        for(let i=0;i<this.opponentSeatParent.children.length;i++){
            let seat = this.opponentSeatParent.children[i]
            seat.getComponent("SeatOther").stopCountting()
        }
        this.playerSeat.getComponent("TPPHead").stopCountting()
    },

    closeWindows:function () {
        this.uiMgrNode.getComponent("GameUIMgr")._hideDealBoard()
    },

    closeDialogs:function () {
        cc.gg.toastMgr.removeDialog()
    },

    onOptionButtonClicked:function (event) {
        let btnName = event.target.name
        if(btnName === "ButtonDiscard"){
            // if(cc.gg.handPokerMgr.selectedEndPokerNodeArray.length > 1){
            //     console.warn("There are more than one card selected,logic error!")
            //     return
            // }
            // this.startDiscardFlow(cc.gg.handPokerMgr.selectedEndPokerNodeArray[0])
        }else if(btnName === "ButtonFinish"){
            cc.gg.dataMgr.pokerCanClick = true
            this.doFinish()
        }else if(btnName === "ButtonGroup"){
            cc.gg.dataMgr.pokerCanClick = true
            let selectingPokerNodes = cc.gg.handPokerMgr.selectedEndPokerNodeArray
            cc.gg.emitEvent("option_group",selectingPokerNodes)

            if(this.gameState === cc.gg.enumConfig.OptionState.GROUP){
                let handCards = this.getCommitArr(this.pokerBottoms,null)
                cc.gg.dataMgr.getPlayerUser().sync(handCards)
            }

            this.scheduleOnce(function () {
                for(let i=0;i<selectingPokerNodes.length;i++){
                    selectingPokerNodes[i].getComponent("PokerModelTs").cancelSelected()
                    selectingPokerNodes.splice(i--,1)
                }
                this.uiMgrNode.emit("ui_show_btn_group",false)
                cc.gg.emitEvent("start_group")
                cc.gg.emitEvent("update_bottoms_width")
            }, 0)
        }else if(btnName === "ButtonDeclare"){
            cc.gg.dataMgr.pokerCanClick = false
            cc.gg.tpgMgr.pokerStackDragable = false
            cc.gg.tpgMgr.canDragHandPokers = false

            this.uiMgrNode.emit("ui_show_btn_declare",false)
            let pokerArray = this.getCommitArr(this.pokerBottoms)
            cc.gg.dataMgr.getPlayerUser().commit(pokerArray)
        }else if(btnName === "PokerStackTPP" && cc.gg.tpgMgr.canGrab){
            if(!cc.gg.dataMgr.playGuild){
                this.changeOptionState(cc.gg.enumConfig.OptionState.PLAY)
                cc.gg.dataMgr.getPlayerUser().grab(cc.gg.enumConfig.GrabFrom.DECK)
            }else {
                let newPokerObj = {id:cc.gg.dataMgr.generateNewPokerId(),poker:"0x27"}
                let lastBot = this.pokerBottoms[this.pokerBottoms.length-1]
                lastBot.pokers.push(newPokerObj)

                cc.gg.emitEvent("flow_grab_player_finish",cc.gg.dataMgr.getPlayerGameId(),newPokerObj)
            }
        }else if(btnName === "ButtonView"){
            this.uiMgr._showDealInfo(true)
        }
    },

    _onFlowStartGroupPassive:function (id,tmpUserObj,finishCard,groupTime) {
        this.someOneFinish = true
        cc.find("Canvas/SoundManager").getComponent("SoundManager").playTurnStartSound()
        let isPoint = cc.gg.dataMgr.room instanceof PointRoom
        let showScoreWhenWaiting = !isPoint
        // if(isPoint) cc.gg.dataMgr.clearAllUserTotalScore()
        cc.find("Canvas/UIManager").emit("ui_init_deal_info_board",tmpUserObj.id,tmpUserObj.cards,showScoreWhenWaiting)
        if(id === cc.gg.dataMgr.getPlayerGameId()){
            this.discardFinishPoker(cc.gg.handPokerMgr.selectedEndPokerNodeArray[0])
            this.changeOptionState(cc.gg.enumConfig.OptionState.CALCULATING)
            cc.gg.emitEvent("start_group")

            this.headNodeDown.getComponent("TPPHead").stopCountting()
            // for(let i=0;i<this.opponentSeatParent.children.length;i++){
            //     let otherScript = this.opponentSeatParent.children[i].getComponent("SeatOther")
            //     if(otherScript.playerInfo.b_state !== cc.gg.enumConfig.ReadyState.DROPED &&
            //         otherScript.playerInfo.b_state !== cc.gg.enumConfig.ReadyState.ELIMINATED){
            //         otherScript.startCountting(groupTime)
            //     }
            // }
            for(let x in cc.gg.dataMgr.users){
                let userObj = cc.gg.dataMgr.users[x]
                this.addCommittingUser(userObj)
            }

            this.uiMgr._showDealInfo(true)
            cc.find("UIManager",this.node).emit("ui_show_view_node",true)
        }else {
            for(let i=0;i<this.opponentSeatParent.children.length;i++){
                let seatOther = this.opponentSeatParent.children[i].getComponent("SeatOther")
                if(!seatOther.playerInfo)
                    continue

                if(seatOther.playerInfo.id === id)
                    seatOther.stopCountting(groupTime)
                else{
                    if(seatOther.playerInfo.b_state !== cc.gg.enumConfig.ReadyState.DROPED &&
                        seatOther.playerInfo.b_state !== cc.gg.enumConfig.ReadyState.ELIMINATED){
                        // seatOther.startCountting(groupTime)
                        this.addCommittingUser(seatOther.playerInfo)
                    }
                }
            }
            let playerUser = cc.gg.dataMgr.getPlayerUser()
            if(playerUser.b_state !== cc.gg.enumConfig.ReadyState.DROPED &&
                playerUser.b_state !== cc.gg.enumConfig.ReadyState.ELIMINATED){
                this.uiMgrNode.emit("ui_show_btn_declare",true)
                // this.headNodeDown.getComponent("TPPHead").startCountting(groupTime)
                this.addCommittingUser(playerUser)
            }else {
                this.uiMgr._showDealInfo(true)
            }

            this.changeOptionState(cc.gg.enumConfig.OptionState.GROUP)
            this.opponentDiscardFinishPoker(id,cc.gg.dataMgr.generateNewPoker(finishCard))
        }
    },

    setPlayCard:function (newObj) {
        cc.log("刚摸的牌：",newObj)
        this.playCard = newObj
    },

    opponentDiscardOnePoker:function (id,poker) {
        // this.soundMgrNode.getComponent("SoundManager").playPokerFlySound()

        let seatNode = this.getSeatByUID(id)
        let worldPos = seatNode.parent.convertToWorldSpaceAR(seatNode.position)
        let nodePos = this.disPokerStack.convertToNodeSpaceAR(worldPos)

        this._animToDiscardStack(nodePos,0.12,poker,function () {
            if(cc.gg.dataMgr.playGuild && cc.gg.dataMgr.guildData.step === 4){
                this.startGuildGrab10()
                cc.gg.dataMgr.guildData.step = 5
            }
        }.bind(this))
    },

    _onRoomOpponentGrap:function (id, from) {
        // this.changeOptionState(cc.gg.enumConfig.OptionState.WAIT)

        this.soundMgrNode.getComponent("SoundManager").playKaPaiSound()
        if(from === cc.gg.enumConfig.GrabFrom.DECK){
            this.opponentGrabOnePoker(id)
        }else if(from === cc.gg.enumConfig.GrabFrom.DISCARDS){
            this.opponentGrabFromDiscards(id)
        }
    },

    opponentGrabOnePoker:function (id) {
        cc.logfl("Opponent grab a poker...")

        let worldPos = this.pokerStackNode.parent.convertToWorldSpaceAR(this.pokerStackNode.position)
        let oriPos = this.pokerStackNode.convertToNodeSpaceAR(worldPos)

        let seatNode = this.getSeatByUID(id)
        let upWorldPos = seatNode.parent.convertToWorldSpaceAR(seatNode.position)
        let upPos = this.pokerStackNode.convertToNodeSpaceAR(upWorldPos)

        let newPoker = cc.instantiate(this.pokerModel)
        this.pokerStackNode.addChild(newPoker)
        newPoker.position = oriPos

        let moveTo = cc.moveTo(0.4,upPos)
        let callfunc = cc.callFunc(function () {
            this.active = false
            this.removeFromParent(true)
        }.bind(newPoker),this)

        let seq = cc.sequence(moveTo,callfunc)
        newPoker.runAction(seq)
    },

    opponentGrabFromDiscards:function (id) {
        let seatNode = this.getSeatByUID(id)
        if(!seatNode){
            cc.error("No seat with id:",id)
            return
        }

        let oppWorldPos = seatNode.parent.convertToWorldSpaceAR(seatNode.position)
        let oppPos = this.disPokerStack.convertToNodeSpaceAR(oppWorldPos)

        let newPoker = cc.gg.disCardMgr.getLastPoker()

        let moveTo = cc.moveTo(0.4,oppPos)
        let callfunc = cc.callFunc(function () {
            this.active = false
            this.destroy()
            cc.gg.baseUtil.arrayRemove(cc.gg.disCardMgr.stackPokerNodes,this)
            cc.gg.disCardMgr.updateDiscardStack(cc.gg.dataMgr.room.getDicards(cc.gg.disCardMgr.stackShowCount))
        }.bind(newPoker),this)

        let seq = cc.sequence(moveTo,callfunc)
        newPoker.runAction(seq)
    },

    initPokerBottoms:function (exceptPokerNode) {
        cc.log("Reset all bottoms by poker Groups")
        this.pokerBottoms = []

        let pokerWidth = this.pokerModel.data.width
        for(let i=0;i<this.pokerGroups.length;i++){
            let group = this.pokerGroups[i]
            if(!group.length)
                continue

            let typeObj = this.getGroupType(group,cc.gg.dataMgr.getMixCardNum())
            this.pokerBottoms.push({
                width:(group.length-1)*this.pokerInterval + pokerWidth + this.bottomMarginLR*2,
                type:typeObj,
                isGreen:typeObj.pure,
                pokers:group,
                pos:null,
                node:null,
            })
            // cc.log("group",group,"的宽度", (group.length-1)*this.pokerInterval + pokerWidth + this.bottomMarginLR*2)
        }

        let totalLength = (this.pokerBottoms.length - 1)*this.groupInterval
        for(let i=0;i<this.pokerBottoms.length;i++){
            let botObj = this.pokerBottoms[i]
            let width = botObj.width
            totalLength += width
        }

        let nowLeftX = - totalLength/2
        for(let i=0;i<this.pokerBottoms.length;i++){
            let botObj = this.pokerBottoms[i]
            let width = botObj.width

            nowLeftX += width/2
            let botPos = cc.v2(nowLeftX,0)
            botObj.pos = botPos

            nowLeftX += width/2 + this.groupInterval
        }


        for(let i=0;i<this.pokerBottoms.length;i++){
            let botObj = this.pokerBottoms[i]
            let botPos = botObj.pos

            let newBottom = cc.instantiate(this.bottomModel)
            newBottom.position = botPos
            newBottom.botObj = botObj
            this.bottomParent.addChild(newBottom)

            botObj.node = newBottom

            let botScript = newBottom.getComponent("SeperateBottom")
            botScript.showBottom(botObj)
        }
        this.scheduleOnce(function () {
            cc.gg.emitEvent("update_bottoms_scores",cc.gg.dataMgr.getPlayerGameId())
        }, 0)


        for(let a=0;a<this.pokerGroups.length;a++){
            let group = this.pokerGroups[a]
            if(!group.length)
                continue

            let botObj = this._getPokerBottomObj(group[0])
            let botPos = botObj.pos
            let botWidth = botObj.width

            let botWorldPos = this.bottomParent.convertToWorldSpaceAR(botPos)
            let nodePos = this.handPokerParent.convertToNodeSpaceAR(botWorldPos)

            //a group of pokers fly to a bottom
            for(let j=0;j<group.length;j++){
                let pokerId = group[j]
                let pokerNode = this._getPokerNodeByPokerId(pokerId.id)
                if(pokerNode === exceptPokerNode)
                    continue

                let x = nodePos.x - botWidth/2 + this.bottomMarginLR + pokerWidth/2 + j * this.pokerInterval
                let y = nodePos.y + this.pokerModel.data.height/2
                let tarPos = cc.v2(x,y)

                let moveTo = cc.moveTo(0.4,tarPos)
                let callfunc = cc.callFunc(function () {
                    let pokerModel = pokerNode.getComponent("PokerModelTs")
                    pokerModel.inHandStatic = true
                    pokerModel.inDispatchAnim = false
                },this)
                let seq = cc.sequence(moveTo,callfunc)
                pokerNode.runAction(seq)

                pokerNode.zIndex = j
            }
        }

        this.scheduleOnce(function () {
            this.onHandPokerSeperateOver()
        }, 0.4)
    },

    _getPokerNodeByPokerId:function (pokerId) {
        let pokerNodes = this.handPokerParent.children
        for(let i=0;i<pokerNodes.length;i++){
            let node = pokerNodes[i]
            let poker = node.poker

            if(poker.id === pokerId){
                return node
            }
        }
        return null
    },

    _getPokerBottomObj:function (pokerId) {
        for(let i=0;i<this.pokerBottoms.length;i++){
            let botObj = this.pokerBottoms[i]
            let pokers = botObj.pokers

            let idx = pokers.indexOf(pokerId)
            if(idx > -1)
                return botObj
        }
        return null
    },

    onHandPokerSeperateOver:function () {
        this.animOpenDeck(
            cc.gg.dataMgr.room.c_open_objs[0],
            cc.gg.dataMgr.getMixCard()
        )
    },

    animOpenDeck:function (discardPoker, mixPoker) {
        let pokerStackPriWorldPos = this.pokerStackNode.parent.convertToWorldSpaceAR(this.pokerStackNode.position)
        let nodePos = this.disPokerStack.convertToNodeSpaceAR(pokerStackPriWorldPos)

        //pick bottom discard
        let newDisCard = cc.instantiate(this.disCardModel)
        newDisCard.position = nodePos
        newDisCard.getComponent("DiscardPokerModel").initDiscardPoker()
        this.disPokerStack.addChild(newDisCard)

        let actArray = []
        actArray.push(cc.moveTo(0.6,cc.Vec2.ZERO))
        actArray.push(cc.scaleTo(0.2, 0, 1.0))
        actArray.push(cc.callFunc(function () {
            newDisCard.getComponent("DiscardPokerModel").initDiscardPoker(discardPoker)
        },this))
        actArray.push(cc.scaleTo(0.2, 1, 1.0))
        actArray.push(cc.removeSelf())
        actArray.push(cc.callFunc(function () {
            // cc.gg.emitEvent("data_discard_one",discardPoker)
            // cc.gg.disCardMgr.initDiscardStack(cc.gg.dataMgr.guildData.bot,cc.gg.dataMgr.generateNewPoker(cc.gg.dataMgr.getMixCard()))

            if(cc.gg.dataMgr.playGuild){
                cc.gg.disCardMgr.updateDiscardStack(cc.gg.dataMgr.guildData.discards)
            }else {
                cc.gg.disCardMgr.updateDiscardStack(cc.gg.dataMgr.room.getDicards(cc.gg.disCardMgr.stackShowCount))
            }
        }.bind(this),this))

        newDisCard.runAction(cc.sequence(actArray))


        //pick mixcard
        let worldPos2 = cc.gg.baseUtil.getWorldPos(this.pokerStackGamePos)
        let botCardTarPos = this.pokerStackNode.parent.convertToNodeSpaceAR(worldPos2)
        let botCardOriPos = this.pokerStackGamePos.convertToNodeSpaceAR(pokerStackPriWorldPos)
        this.scheduleOnce(function () {
            let newBotCard = cc.instantiate(this.disCardModel)
            newBotCard.position = botCardOriPos
            newBotCard.getComponent("DiscardPokerModel").initDiscardPoker()
            this.pokerStackGamePos.addChild(newBotCard)

            let array1 = []
            array1.push(cc.scaleTo(0.2, 0, 1.0))
            array1.push(cc.callFunc(function () {
                newBotCard.getComponent("DiscardPokerModel").initDiscardPoker(mixPoker)
            },this))
            array1.push(cc.scaleTo(0.2, 1, 1.0))
            let changeAnim = cc.sequence(array1)
            let spawn = cc.spawn(changeAnim,cc.rotateTo(0.6,90))

            let actArray = []
            actArray.push(cc.moveTo(0.6,cc.v2(-40,0)))
            actArray.push(spawn)

            newBotCard.runAction(cc.sequence(actArray))
        }, 0.6)

        //move deck to left
        this.scheduleOnce(function () {
            let callfunc = cc.callFunc(function () {
                //开始刚才由于展示发牌动画而停止的牌库闪烁
                if(this.deckBlinking){
                    this.pokerStackBlink()
                }
                if(cc.gg.dataMgr.playGuild){
                    cc.loader.loadRes("Guild/Guild2",cc.Prefab,function (err, prefab) {
                        let newNode = cc.instantiate(prefab)
                        this.node.addChild(newNode)
                        this.nodeGuild2 = newNode

                        cc.gg.baseUtil.addClickEventToNode(cc.find("Step1/bContinue2",newNode),this.node,LogicConfigTs.SCENENAME_GAME_2,"onGuildButtonClicked")
                        cc.gg.baseUtil.addClickEventToNode(cc.find("Step2/BtnDeckStep2",newNode),this.node,LogicConfigTs.SCENENAME_GAME_2,"onGuildButtonClicked")
                        cc.gg.baseUtil.addClickEventToNode(cc.find("Step2/BtnDisStep2",newNode),this.node,LogicConfigTs.SCENENAME_GAME_2,"onGuildButtonClicked")
                    }.bind(this))
                }


                this._animDispatching = false
            }.bind(this),this)

            let seq = cc.sequence(
                cc.moveTo(0.6,botCardTarPos),
                callfunc,
            )
            this.pokerStackNode.runAction(seq)
        }.bind(this),1.4)
    },


    changeOptionState:function (data) {
        this.gameState = data

        cc.find("Canvas").emit("msgwatcher_add",function () {
            let uiMgr = this.uiMgr.getComponent("GameUIMgr")
            if(uiMgr.optNode){
                this.uiMgr.changeOptionStateUI(data)
                return true
            }
            return false
        }.bind(this))
        cc.logfl("开始客户端阶段：",data)

        //todo b_state dispatching
        if(data === cc.gg.enumConfig.OptionState.DISPATCHING){
            cc.gg.tpgMgr.canDiscard = false             //able to discard a hand poker
            cc.gg.tpgMgr.canDragHandPokers = false      //able to ajudge sequence of hand pokers by draging
            cc.gg.tpgMgr.canGrab = false                //can grab from deck or discards stack
            this.pokerStackBlinkStop()
        }else if(data === cc.gg.enumConfig.OptionState.WAIT){
            cc.gg.tpgMgr.canDragHandPokers = true
            cc.gg.dataMgr.pokerCanClick = true
            cc.gg.tpgMgr.canDiscard = false
            cc.gg.tpgMgr.pokerStackDragable = false
            cc.gg.tpgMgr.canGrab = false
            this.pokerStackBlinkStop()
        }else if(data === cc.gg.enumConfig.OptionState.GRAB){
            cc.gg.tpgMgr.canDiscard = false
            cc.gg.tpgMgr.pokerStackDragable = true
            cc.gg.tpgMgr.canDragHandPokers = true
            cc.gg.tpgMgr.canGrab = true
            cc.gg.toastMgr.showToast(LanguageMng.getSentence(69))
            this.pokerStackBlink()
        }else if(data === cc.gg.enumConfig.OptionState.PLAY){
            cc.gg.tpgMgr.canDiscard = true
            cc.gg.tpgMgr.canDragHandPokers = true
            cc.gg.tpgMgr.pokerStackDragable = false
            cc.gg.tpgMgr.canGrab = false
            this.pokerStackBlinkStop()
        }else if(data === cc.gg.enumConfig.OptionState.GROUP){
            cc.gg.tpgMgr.canDragHandPokers = true
            cc.gg.tpgMgr.canDiscard = false
            this.pokerStackBlinkStop()
        }else if(data === cc.gg.enumConfig.OptionState.CALCULATING){
            cc.gg.tpgMgr.canDiscard = false
            this.pokerStackBlinkStop()
        }
    },

    getSeatByUID:function (id) {
        if(id === cc.gg.dataMgr.getPlayerGameId()) return this.playerSeat

        if(cc.gg.dataMgr.playGuild) return this.opponentSeatParent.children[0]

        for(let i=0;i<this.opponentSeatParent.children.length;i++){
            let script = this.opponentSeatParent.children[i].getComponent("SeatOther")
            if(!script.playerInfo) continue
            if(script.playerInfo.id === id)
                return this.opponentSeatParent.children[i]
        }

        return null
    },

    getEmptySeat:function () {
        let seats = this.opponentSeatParent.children
        for(let i=seats.length-1;i>-1;i--){
            if(!seats[i].getComponent("SeatOther").playerInfo)
                return seats[i]
        }

        return null
    },

    getSeatByUserIdx:function (playerSeatNo, no) {
        let minus = playerSeatNo - 1
        let clientIdx = no
        if(minus){
            if(no > playerSeatNo){
                clientIdx = no - minus
            }else {
                clientIdx = 6 - minus + no
            }
        }

        let seats = this.opponentSeatParent.children
        cc.log("clientIdx:",clientIdx)
        return seats[seats.length - clientIdx + 1]
        // for(let i=seats.length-1;i>-1;i--){
        //     if(!seats[i].getComponent("SeatOther").playerInfo)
        //         return seats[i]
        // }
        //
        // return null
    },

    // let test = function (playerSeatNo,no) {
    //     let minus = playerSeatNo - 1
    //     if(minus){
    //         let clientIdx = no
    //         if(no > playerSeatNo){
    //             clientIdx = no - minus
    //         }else {
    //             clientIdx = 6 - minus + no
    //         }
    //         let seats = ["s1","s2","s3","s4","s5"]
    //         return seats[seats.length - clientIdx + 1]
    //     }else {
    //         let seats = ["s1","s2","s3","s4","s5"]
    //         return seats[seats.length - no + 1]
    //     }
    //
    // }
    //
    // for(let i=1;i<=6;i++){
    //     for(let j=1;j<=6;j++){
    //         if(i === j) continue
    //         let seatName = test(i,j)
    //         cc.log("玩家No是",i," 其他玩家是",j," 玩家坐到了",seatName)
    //     }
    // }
    //get poker value array to commit to server
    getCommitArr:function (pokerBottoms, exceptPokerObj) {
        let pokerArray = []
        for(let i=0;i<pokerBottoms.length;i++){
            let bot = pokerBottoms[i]
            let groupArr = []
            for(let j=0;j<bot.pokers.length;j++){
                if(bot.pokers[j] === exceptPokerObj)
                    continue

                groupArr.push(cc.gg.dataMgr.convToServerPokerValue(bot.pokers[j].poker))
            }
            if(groupArr.length) pokerArray.push(groupArr)
        }
        return pokerArray
    },

    //不可靠
    getPokerNodeByPokerValue:function (pokervalue) {
        let pokerNodes = this.handPokerParent.children
        for(let i=0;i<pokerNodes.length;i++){
            let node = pokerNodes[i]
            let poker = node.poker

            if(poker.poker === pokervalue){
                return node
            }
        }
        return null
    },


    get13EmptyArray:function () {
        return [
            [],[],[],[],
            [],[],[],[],
            [],[],[],[],
            [],[],[],[]
        ]
    },

    convertToSinglePokerArray:function (pokerCalArray) {
        let singleArray = []
        for(let i=0;i<pokerCalArray.length;i++){
            let samePokers = pokerCalArray[i]
            for(let j=0;j<samePokers.length;j++){
                let single = samePokers[j]
                singleArray.push(single)
            }
        }

        return singleArray
    },

    pokerStackBlink:function () {
        this.deckBlinking = true

        // this.disPokerStack.emit("ui_dispokerstack_start_blink")

        let borderNode = this.disPokerStack.getChildByName("Border")
        borderNode.active = true
        borderNode.stopAllActions()

        var fadeIn1 = cc.fadeIn(0.8)
        var fadeOut1 = cc.fadeOut(0.8)
        let seq1 = cc.sequence(fadeIn1,fadeOut1)
        let repeat1 = cc.repeatForever(seq1)

        borderNode.opacity = 0
        borderNode.runAction(repeat1)



        let stackBorder = this.pokerStackNode.getChildByName("Border")
        stackBorder.active = true

        var fadeIn = cc.fadeIn(0.8)
        var fadeOut = cc.fadeOut(0.8)
        let seq = cc.sequence(fadeIn,fadeOut)
        let repeat = cc.repeatForever(seq)

        stackBorder.opacity = 0
        stackBorder.runAction(repeat)
    },

    pokerStackBlinkStop:function () {
        this.deckBlinking = false
        let disBorder = this.disPokerStack.getChildByName("Border")
        disBorder.active = false
        let stackBorder = this.pokerStackNode.getChildByName("Border")
        stackBorder.active = false
    },

    getRestoreCards:function (resCards) {

        //convert pokers to client point
        var pokerGroups = []
        for(let i=0;i<resCards.length;i++){
            let cards = resCards[i]
            let objs = []

            for(let j=0;j<cards.length;j++){
                let clientNum = cc.gg.dataMgr.convToClientPokerValue(cards[j])
                objs.push(cc.gg.dataMgr.generateNewPoker(clientNum))
            }

            pokerGroups.push(objs)
        }
        return pokerGroups
    },


    doMixScoreArray:function (pokerArray, mixCards) {

        if(!mixCards.length)
            return

        let mixCopy = [].concat(mixCards)
        let mixScoreArray = []
        //calculate where mix should be put
        for(let i=1;i<pokerArray.length;i++){
            if(pokerArray[i].length){
                continue
            }

            let preCount = this._searchPrevious(i,pokerArray)
            let followCount = this._searchAfter(i,pokerArray)

            if(!preCount && followCount < 2)
                continue

            if(!followCount && preCount < 2)
                continue

            let score = 0
            if(preCount >=2 && followCount === 0){
                score = 1
            }else if(followCount >= 2 && preCount === 0){
                score = 1
            }else if(followCount === 1 && preCount === 1){
                score = 1
            }else if(preCount >=2 && followCount > 0){
                score = 2
            }else if(followCount >=2 && preCount > 0){
                score = 2
            }else {
                cc.error("发现了尚未处理的混子得分！")
            }

            mixScoreArray.push({
                score:score,
                pokerObj:mixCopy.pop(),
                index:i
            })

            if(mixCopy.length === 0)
                break
        }

        if(!mixScoreArray.length)
            return

        mixScoreArray.sort(function (a, b) {
            a.score - b.score
        })

        let mvp = mixScoreArray[0]
        pokerArray[mvp.index].push(mvp.pokerObj)

        cc.gg.baseUtil.arrayRemove(mixCards,mvp.pokerObj)
        // mixCards.remove(mvp.pokerObj)
    },

    _searchPrevious:function (mixIdx,allBlack) {
        let duanLe1 = false
        let seqCount = 0
        for(let fromIdx = mixIdx-1;fromIdx>0;fromIdx--){
            if(!duanLe1 && allBlack[fromIdx].length){
                seqCount++
            }else {
                duanLe1 = true
            }
        }

        // cc.log("向前试探，得分：",seqCount)
        return seqCount
    },

    _searchAfter:function (mixIdx,allBlack) {
        let seqCount2 = 0
        let duanLe = false
        for(let fromIdx = mixIdx+1;fromIdx<allBlack.length;fromIdx++){
            if(!duanLe && allBlack[fromIdx].length){
                seqCount2++
            }else{
                duanLe = true
            }
        }

        // cc.log("向后试探，得分：",seqCount2)
        return seqCount2
    },

    startWaitCountDown(maxTime){
        cc.log("+++++++开始等人倒计时+++++++")
        this.uiMgr._onGameCountDownStart(maxTime);
    },

    initHandCardBottomsWithMixCard:function (handPokers, mixCardId) {

        this.pokerGroups = []

        let allBlack = this.get13EmptyArray()
        let allHearts = this.get13EmptyArray()
        let allFLowers = this.get13EmptyArray()
        let allDiamonds = this.get13EmptyArray()
        let allJokers = this.get13EmptyArray()
        let mixCards = []

        let mixNum = cc.gg.dataMgr.getPokerNum(mixCardId)

        for(let i=0;i<handPokers.length;i++){

            let pokerObj = handPokers[i]
            let card = pokerObj.poker
            let num = cc.gg.dataMgr.getPokerNum(card)

            if(mixNum === num){
                mixCards.push(pokerObj)
                continue
            }

            if(cc.gg.dataMgr.getPokerHua(card) === cc.gg.enumConfig.FLOWER.BLACK){
                allBlack[num].push(pokerObj)
            }else if(cc.gg.dataMgr.getPokerHua(card) === cc.gg.enumConfig.FLOWER.HEART){
                allHearts[num].push(pokerObj)
            }else if(cc.gg.dataMgr.getPokerHua(card) === cc.gg.enumConfig.FLOWER.FLOWER){
                allFLowers[num].push(pokerObj)
            }else if(cc.gg.dataMgr.getPokerHua(card) === cc.gg.enumConfig.FLOWER.DIAMOND){
                allDiamonds[num].push(pokerObj)
            }else if(cc.gg.dataMgr.getPokerHua(card) === cc.gg.enumConfig.FLOWER.JOKER){
                mixCards.push(pokerObj)
            }
        }

        if(mixCards.length){
            this.doMixScoreArray(allBlack,mixCards)
            this.doMixScoreArray(allHearts,mixCards)
            this.doMixScoreArray(allFLowers,mixCards)
            this.doMixScoreArray(allDiamonds,mixCards)
        }

        if(mixCards.length){
            for(let i=0;i<mixCards.length;i++){
                let tmpMix = mixCards[i]
                let flower = cc.gg.dataMgr.getPokerHua(tmpMix)
                let num = cc.gg.dataMgr.getPokerNum(tmpMix)

                if(flower === cc.gg.enumConfig.FLOWER.BLACK){
                    allBlack[num].push(tmpMix)
                }else if(flower === cc.gg.enumConfig.FLOWER.HEART){
                    allHearts[num].push(tmpMix)
                }else if(flower === cc.gg.enumConfig.FLOWER.FLOWER){
                    allFLowers[num].push(tmpMix)
                }else if(flower === cc.gg.enumConfig.FLOWER.DIAMOND){
                    allDiamonds[num].push(tmpMix)
                }else if(flower === cc.gg.enumConfig.FLOWER.JOKER){
                    //TODO JOKER is independent
                    allJokers[num].push(tmpMix)
                }else {
                    cc.error("Unknown flower type!")
                    return
                }
            }
        }


        this.pokerGroups.push(this.convertToSinglePokerArray(allBlack))
        this.pokerGroups.push(this.convertToSinglePokerArray(allHearts))
        this.pokerGroups.push(this.convertToSinglePokerArray(allFLowers))
        this.pokerGroups.push(this.convertToSinglePokerArray(allDiamonds))
        this.pokerGroups.push(this.convertToSinglePokerArray(allJokers))

        cc.log("seperate over:",this.pokerGroups)
    },

    getGroupType:function (sameFlowerArray, mixCardNum) {

        let isAllMix = true
        for(let i=0;i<sameFlowerArray.length;i++){
            if(!cc.gg.dataMgr.isJoker(sameFlowerArray[i].poker) && !cc.gg.dataMgr.isMixCard(sameFlowerArray[i].poker,mixCardNum)){
                isAllMix = false
                break
            }
        }

        if(isAllMix) return {
            type:cc.gg.enumConfig.SeperateType.ALL_MIX,
            pure:false
        }

        if(sameFlowerArray.length < 2){
            return {
                type:cc.gg.enumConfig.SeperateType.INVALID,
                pure:false
            }
        }

        let seqJudgeObj = cc.gg.sortUtil.IS_SEQUENCE(sameFlowerArray,mixCardNum)
        let isSeq = seqJudgeObj.isSequence
        let isPure = seqJudgeObj.isPure


        if(isSeq){
            return {
                type:cc.gg.enumConfig.SeperateType.SEQUENCE,
                pure:isPure
            }
        }

        let isSet = cc.gg.sortUtil.isSet(sameFlowerArray,mixCardNum)
        if(isSet){
            return {
                type:cc.gg.enumConfig.SeperateType.SET,
                pure:false
            }
        }

        return {
            type:cc.gg.enumConfig.SeperateType.INVALID,
            pure:false
        }
    },

});
